//
//  RegisterViewController.m
//  1505BmobDemo
//
//  Created by HeHui on 16/1/7.
//  Copyright (c) 2016年 Hawie. All rights reserved.
//

#import "RegisterViewController.h"
#import "MyButton.h"
#import "Tool.h"


@interface RegisterViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF1;
@property (weak, nonatomic) IBOutlet UITextField *emailTF;
@property (weak, nonatomic) IBOutlet MyButton *registerBtn;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkTextFields];
    // Do any additional setup after loading the view.
}

- (IBAction)userNameEditingChanged:(UITextField *)sender {
    [self checkTextFields];
}

- (IBAction)passwordTFEditingChanged:(UITextField *)sender {
    [self checkTextFields];
}

- (void) checkTextFields
{
    // 当两个textfiled里面都有值的时候才让 注册按钮可点，否则不可点
    if (self.userNameTF.text.length > 0 && self.passwordTF.text.length > 0) {
        self.registerBtn.enabled = YES;
    }else {
        self.registerBtn.enabled = NO;
    }
    
}
- (IBAction)registerBtnPressed:(MyButton *)sender {
    
    // 创建一个用户对象
    BmobUser *user = [[BmobUser alloc] init];
    // 设置用户的账号密码
    user.username = self.userNameTF.text;
    
    NSString *pwdMD5Str = [Tool MD5StringFromString:self.passwordTF.text];
    
    user.password = pwdMD5Str;
    
    if (self.emailTF.text.length > 0) {
        user.email = self.emailTF.text;
    }
    
    // 如果填写有邮箱，会自动给邮箱发送一条验证邮件
    [user signUpInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            [SVProgressHUD showSuccessWithStatus:@"注册成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        }
    }];
    
}

@end
